package org.noote.test_camerasurface;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.noote.libs.camera.surface.CameraSurface;
import org.noote.libs.camera.helper.Helper_Camera;
import org.noote.libs.graphicbuffer.GraphicBuffer;
import org.noote.libs.graphicbuffer.GraphicView;
import org.noote.libs.graphicbuffer.FPSCounter;

@SuppressLint("HandlerLeak")
public class TestCameraSurface_Activity extends Activity {
	protected static final int MSG_UPDATE_FPSCOUNTER = 0;
	
	private GraphicView mView;
	private CameraSurface _camera = new CameraSurface();
	private FPSCounter mFPSCounter = new FPSCounter();

	public class CameraPreviewListener implements org.noote.libs.camera.listener.CameraPreviewListener {
		@Override
		public void onStartPreview() {
			// TODO Auto-generated method stub
		}
		
		@Override
		public void onGrabbedFrame(GraphicBuffer frame) {
			mView.push(frame);
			mFPSCounter.tick();
			mHandler.sendMessage(mHandler.obtainMessage(MSG_UPDATE_FPSCOUNTER, null));
		}

		@Override
		public void onStopPreview() {
			// TODO Auto-generated method stub
		}
	}
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		if(Helper_Camera.checkCameraHardware(getApplicationContext()))
		{
			mView = new GraphicView(this);
			((FrameLayout) findViewById(R.id.layoutPreview)).addView(mView);

			_camera.setPreviewListener(new CameraPreviewListener());
		}
		else
		{
			Toast.makeText(getApplicationContext(), "Your device have no camera !", Toast.LENGTH_LONG).show();
		}
		
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
	}

	@Override
    protected void onResume() {
        super.onResume();
		if(_camera.open(Helper_Camera.getCamera()))
		{
			_camera.startPreview();
		}
		else
		{
			Toast.makeText(getApplicationContext(), "Cannot open camera !", Toast.LENGTH_LONG).show();
		}
    }

	@Override
    protected void onPause() {
		_camera.close();
		
        super.onPause();        
    }

	final Handler mHandler = new Handler() {
	    @Override
		public void handleMessage(Message msg) {
	        switch (msg.what) {
	        case MSG_UPDATE_FPSCOUNTER:
	        	TextView fps = (TextView) findViewById(R.id.textViewFPS);
	        	fps.setText("Capture : " + mFPSCounter.getFPS() + " i/s");
	        	
	            break;
	        }
	    }
	};

}
